<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/10/16
 * Time: 23:22
 */

namespace App\Service;


use App\Exceptions\WechatException;
use App\Jobs\LostAudit;
use App\Jobs\LostNotify;
use App\Jobs\SaveUserPhone;
use App\Jobs\SendTemplate;
use App\Model\Lost;
use App\Repository\LostRepository;
use App\Repository\UserRepository;
use QiniuService;

class LostService
{

    protected $user;

    protected $lost;

    public function __construct(UserRepository $user, LostRepository $lost)
    {
        $this->user = $user;
        $this->lost = $lost;
    }

    /**
     * 发布招领
     *
     * @param $openId
     * @param $mediaId
     * @param $description
     * @param $number
     * @param $shortNumber
     * @param $cellphone
     * @return \App\Model\Lost
     * @internal param $class
     * @internal param $college
     */
    public function publish($openId, $mediaId, $description, $number, $shortNumber, $cellphone)
    {
        $this->validPublish($openId, $number, $description);

        $cover = $this->postCoverToQiniu($mediaId);

        $lost = $this->lost->add($openId, $cover, $description, $number);

        dispatch(new SaveUserPhone($openId, $shortNumber, $cellphone));
        dispatch(new LostAudit($lost));

        return $lost;
    }

    /**
     * 上传图片到七牛并且返回图片
     *
     * @param $mediaId
     * @return null
     */
    private function postCoverToQiniu($mediaId)
    {
        if(!$mediaId) return null;

        $file = $this->generateFileName($mediaId);

        $content = app('wechat')->material_temporary->getStream($mediaId);

        return QiniuService::put($file, $content);
    }

    /**
     * 能否发布
     *
     * @param $openId
     * @param $number
     * @param $description
     * @return bool
     * @throws WechatException
     */
    private function validPublish($openId, $number, $description)
    {
        $publisher = $this->user->getUserByOpenId($openId);

        if($this->lost->sameLostToday($number, $description)){
            throw new WechatException('该招领今天已发布', 401);
        }

        if($publisher->admin && $publisher->admin->can('lost_publish')){
            return true;
        }

        if($this->lost->getByPublisher($openId, true)){
            throw new WechatException('一天只能发一次招领', 401);
        }

        if($this->user->isClassmate($publisher->number, $number)){
            throw new WechatException('别闹了，都是好基友，别以为小哥我不知道', 401);
        }
    }

    /**
     * 生成七牛文件名
     *
     * @param $mediaId
     * @return string
     */
    private function generateFileName($mediaId)
    {
        return 'lost/' . $mediaId . '.png';
    }

    /**
     * 根据ID更改失主信息
     *
     * @param $id
     * @return LostRepository|bool
     */
    public function updateUserOfLost($id)
    {
        $lost = $this->lost->find($id);

        if(!$lost || !$lost->number)
            return false;

        $user = \BindService::getUserInfo($lost->number);

        if($user){
            $lost->update(['class' => $user['class'], 'name' => $user['name']]);
            return $user;
        }else{
            return false;
        }
    }

    /**
     * 审核
     *
     * @param $id
     * @param $status
     * @return bool
     */
    public function audit($id, $status)
    {
        if($this->lost->changeStatus($id, $status)){

            $lost = $this->lost->find($id);

            if($status == Lost::AUDITED){

                dispatch(new LostNotify($lost));

            }

            $data = [
                'first' => "您好，你的招领发布已审核完毕",
                'keyword1' => $lost->description,
                'keyword2' => $status == Lost::AUDITED ? '审核通过' : '审核不通过',
                'remark' => $status == Lost::AUDITED ? '计协小哥感谢你的贡献，拾金不昧，从这里开始' : '对不起，你的发布审核不通过，请检查失物图片是否能够看清楚学号信息',
            ];

            dispatch(new SendTemplate($data, env('APP_URL') . 'lost', $lost->publisher, 'lost_result'));

            return true;
        }

        return false;
    }

}